package com.sm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.sm.ali.entity.AliPayBean;
import com.sm.model.HappyOrder;
import com.sm.model.HappyRequest;
import com.sm.service.*;
import com.sm.model.Order;
import com.sm.service.MyVipService;
import com.sm.service.OrderService;
import com.sm.service.UserVipOrderService;
import com.sm.service.VipActivitiesOrderService;
import com.sm.util.Msg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**支付宝微信订单异步回调
 *
 * @author 60915
 */
@Slf4j
@Controller
@RequestMapping("/payment")
public class PaymentController {
    @Autowired
    private AliPayBean aliPayBean;
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserVipOrderService userVipOrderService;

    @Autowired
    private MyVipService myVipService;
    @Autowired
    private VipActivitiesOrderService vipActivitiesOrderService;

    @Autowired
    private HappyOrderService happyOrderService;


    @RequestMapping("/notify")
    @ResponseBody
    public String notify(String orderNum) {
        Integer vipOrderStatus = userVipOrderService.getVipOrderStatus(orderNum);
        if (vipOrderStatus != null && vipOrderStatus == 0) {
            myVipService.notifyInsert(orderNum);
        }
        return "1";
    }

    /**
     * 支付宝圆梦超市下单异步回调
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/aliSuperMarketNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String aliSuperMarketNotify(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCertCheckV1(params, aliPayBean.getAliPayCertPath(), "UTF-8", "RSA2");
            if (verifyResult) {
                //订单号
                String orderNum = params.get("out_trade_no");
                log.info("回调拿到订单号：{}", orderNum);
                boolean isFinish = orderService.getIsFinish(orderNum);
                log.info("当前订单状态:{}",isFinish?"已支付":"未支付");
                if (!isFinish) {
                    orderService.notifyOrderStatus(orderNum);
                }
                return "success";
            } else {
                System.out.println("certNotifyUrl 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }


    /**
     * 微信圆梦超市下单异步回调
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/superMarketNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String superMarketNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        log.info("圆梦超市下单异步回调：params{}", params);
        String returnCode = params.get("return_code");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                String orderNum = params.get("out_trade_no");
                log.info("回调拿到订单号：{}", orderNum);
                boolean isFinish = orderService.getIsFinish(orderNum);
                log.info("当前订单状态:{}",isFinish?"已支付":"未支付");
                if (!isFinish) {
                    orderService.notifyOrderStatus(orderNum);
                }
                log.info("订单处理结束，给微信发通知");
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }

    /**
     * 微信圆梦超市二次下单异步回调
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/superMarketAgainNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String superMarketAgainNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        log.info("圆梦超市重新下单异步回调：params{}", params);
        String returnCode = params.get("return_code");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                String orderNum = params.get("out_trade_no");
                log.info("圆梦超市重新下单拿到微信传来订单号：{}", orderNum);
                Order orderStatusByOrderOn = orderService.getOrderStatusByOrderOn(orderNum);

                if (orderStatusByOrderOn != null && orderStatusByOrderOn.getOrderStatus().equals(-2)) {
                    log.info("圆梦超市重新下单查到数据库订单信息：{}", orderStatusByOrderOn.toString());
                    orderService.notifyOrderStatusByOrderOn(orderNum);
                }
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }


    /**
     * 支付宝圆梦超市重新下单阿里云回调
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/aliSuperMarketAgainNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String aliSuperMarketAgainNotify(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCertCheckV1(params, aliPayBean.getAliPayCertPath(), "UTF-8", "RSA2");
            if (verifyResult) {
                //订单号
                String orderNum = params.get("out_trade_no");
                log.info("圆梦超市重新下单拿到微信传来订单号：{}", orderNum);
                Order orderStatusByOrderOn = orderService.getOrderStatusByOrderOn(orderNum);

                if (orderStatusByOrderOn != null && orderStatusByOrderOn.getOrderStatus().equals(-2)) {
                    log.info("圆梦超市重新下单查到数据库订单信息：{}", orderStatusByOrderOn.toString());
                    orderService.notifyOrderStatusByOrderOn(orderNum);
                }
                return "success";
            } else {
                System.out.println("certNotifyUrl 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }



    /**
     * 微信VIP下单异步回调
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/vipOrderNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String vipOrderNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        log.info("VIP下单异步回调：params{}", params);
        String returnCode = params.get("return_code");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                //订单编号
                String orderNum = params.get("out_trade_no");
                Integer vipOrderStatus = userVipOrderService.getVipOrderStatus(orderNum);
                if (vipOrderStatus != null && vipOrderStatus == 0) {
                    myVipService.notifyInsert(orderNum);
                }
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }



    /**
     *  支付宝VIP下单异步回调
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/aliVipOrderNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String aliVipOrderNotify(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCertCheckV1(params, aliPayBean.getAliPayCertPath(), "UTF-8", "RSA2");
            if (verifyResult) {
                // 更新订单信息
                //订单编号
                String orderNum = params.get("out_trade_no");
                Integer vipOrderStatus = userVipOrderService.getVipOrderStatus(orderNum);
                if (vipOrderStatus != null && vipOrderStatus == 0) {
                    myVipService.notifyInsert(orderNum);
                }
                return "success";
            } else {
                System.out.println("certNotifyUrl 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }


    /**
     * 参会券订单表异步回调
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/activitiesNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String activitiesNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        log.info("参会券下单异步回调：params{}", params);
        String returnCode = params.get("return_code");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                String orderNum = params.get("out_trade_no");
                log.info("回调拿到订单号：{}", orderNum);
                boolean isFinish = vipActivitiesOrderService.getIsFinish(orderNum);
                log.info("当前订单状态:{}",isFinish?"已支付":"未支付");
                if (!isFinish) {
                    vipActivitiesOrderService.notifyActivitiesOrder(orderNum);
                }
                log.info("订单处理结束，给微信发通知");
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }


    /**
     * 幸福问答提问异步回调
     */
    @ResponseBody
    @RequestMapping(value = "/happyNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String happyNotify(HttpServletRequest request){
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        log.info("幸福问答支付提问异步回调：params{}", params);
        String returnCode = params.get("return_code");
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                String orderNum = params.get("out_trade_no");
                boolean isFinish = happyOrderService.getIsFinish(orderNum);
                if (!isFinish) {
                    happyOrderService.updateHappyOrder(orderNum);
                }
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }


}






























